<template>
  <q-dialog  v-model="openOrderHistory">
      <OrderHistorylv2Table :stock-code="stock_code" :serial_no="serial_no"></OrderHistorylv2Table>
  </q-dialog>
  <q-card-actions align="right">
    <!-- <q-btn class="default-btn" @click="newfitmentDialog = true"
        >Fitment</q-btn
      > -->
    <!--  <q-btn class="grey-btn" @click="defitmentDialog=true">defitment</q-btn> -->
    <q-dialog v-model="newfitmentDialog">
      <FitmentBox :actions="'Fitment'" @update="fitment"></FitmentBox>
    </q-dialog>
    <q-dialog v-model="defitmentDialog">
      <MyDialog
        title="Defitment"
        :content="`Defit: Stock Code: ${editedRow.stock_code} , Serial No :${editedRow.serial_no}`"
        :ok="() => defitment()"
      >
      </MyDialog>
    </q-dialog>
  </q-card-actions>
  <ScrollArea :bot-margin="50">
    <div v-if="props.style == 'list'" class="">
      <q-card class="row" style="width: 100%; margin-bottom: 2rem">
        <table class="col-12">
          <thead>
            <tr class="row q-ma-sm">
              <!-- <th class="col-4 fac word-wrap ">Sequence</th> -->
              <th class="col-1 fac word-wrap"></th>
              <th class="col-3 fac word-wrap">Short Description</th>
              <th class="col-4 fac word-wrap">Serial No</th>
              <th class="col-2 fac word-wrap">Latest Status</th>
              <th class="col-2 fac word-wrap">Action</th>
              <!-- <th class="col-6 fac word-wrap ">Action</th> -->
            </tr>
          </thead>

          <tbody v-if="parent">
            <tr
              v-for="(item, index) in Object.entries(parent.child).sort(
                (a, b) => a[1].sequence - b[1].sequence
              )"
              :key="index"
              class="row list-item"
              :class="[
                getPartsStatus(
                  item[1].serial_no,
                  item[1].stock_code,
                  item[1].sw_ver,
                  item[1].hw_ver
                )?.includes('fail')
                  ? 'fail'
                  : getPartsStatus(
                      item[1].serial_no,
                      item[1].stock_code,
                      item[1].sw_ver,
                      item[1].hw_ver
                    )?.includes('pass')
                  ? 'pass'
                  : getPartsStatus(
                      item[1].serial_no,
                      item[1].stock_code,
                      item[1].sw_ver,
                      item[1].hw_ver
                    ),
              ]"
            >
              <q-tooltip class="bg-indigo" :offset="[10, 10]">
                <div class="text-left">
                  <div
                    v-for="(p, index) in getPartsStatus(
                      item[1].serial_no,
                      item[1].stock_code,
                      item[1].sw_ver,
                      item[1].hw_ver
                    )?.split(',')"
                    :key="index"
                  >
                    {{ p }}
                  </div>
                </div>
              </q-tooltip>
              <!-- :class="getPartsStatus(item[1].last_status)" -->
              <!-- <td class="col-6 fac word-wrap ">{{ item[1].sequence }}</td> -->
              <td class="col-1 fac word-wrap">{{ item[1].sequence + 1 }}</td>
              <td class="col-3 fac word-wrap">{{ item[1].description }}</td>
              <td class="col-4 fac word-wrap">{{ item[1].serial_no }}</td>
              <td class="col-2 fac word-wrap">
                <div class="row justify-center">
                  <div
                    class="status-box"
                    :class="getOrderStatusColor(item[1].last_status)"
                  ></div>
                  <div class="fac word-wrap">
                    {{ item[1].last_status }}
                  </div>
                </div>
              </td>
              <td class="col-2 text-center">
                <q-btn
                  class="q-px-sm e-form-btn"
                  size="sm"
                  rounded
                  style="color: #2c37b4"
                  @click="openFitment(item[1].stock_code, item[1].sequence)"
                >
                  <!--  @click="deleteFn(index, item.serial_no)" -->
                  <div class="fac word-wrap">
                    <!-- <img :src="defitIcon" /> -->
                    <span class="q-px-sm cap"> fit </span>
                  </div>
                </q-btn>
                <q-btn
                  class="q-px-sm q-ma-sm e-form-btn"
                  size="sm"
                  rounded
                  style="color: #b42c2c"
                  @click="defitmentFn(item[1].stock_code, item[1].serial_no)"
                >
                  <!--  @click="deleteFn(index, item.serial_no)" -->
                  <div class="fac word-wrap">
                    <!-- <img :src="defitIcon" /> -->
                    <span class="q-px-sm cap"> defit </span>
                  </div>
                </q-btn>
              </td>
            </tr>
          </tbody>
        </table>
      </q-card>
    </div>
    <div v-if="props.style == 'card' && parent">
      {{ `Short Description: ${parent.description}, Stock Code: ${parent.stock_code}, Serial No: ${parent.serial_no}, Car:${parent.car}` }}
      <q-btn flat color="primary" icon="history" @click="openOrderHistoryFn(parent.stock_code,parent.serial_no)"></q-btn>
      
      <div
        v-for="(item, index) in Object.entries(parent.child).sort(
          (a, b) => a[1].sequence - b[1].sequence
        )"
        :key="index"
        class="list-item"
        :class="[
          getPartsStatus(
            item[1].serial_no,
            item[1].stock_code,
            item[1].sw_ver,
            item[1].hw_ver
          )?.includes('fail')
            ? 'fail'
            : getPartsStatus(
                item[1].serial_no,
                item[1].stock_code,
                item[1].sw_ver,
                item[1].hw_ver
              )?.includes('pass')
            ? 'pass'
            : getPartsStatus(
                item[1].serial_no,
                item[1].stock_code,
                item[1].sw_ver,
                item[1].hw_ver
              ),
        ]"
      >
        <q-card-section class="row justify-between">
          <div>
            <div class="cap word-wrap row justify-between">
              Sequence: {{ item[1].sequence + 1 }}
            </div>

            <div class="cap word-wrap row justify-between">
              Short Description: {{ item[1].description }}
            </div>

            <div class="cap word-wrap row justify-between">
              Stock Code: {{ item[1].stock_code }}
            </div>

            <div class="cap word-wrap row justify-between">
              <span>
                Serial No: {{ item[1].serial_no }}
                <div>
                  <q-btn
                    class="q-px-sm e-form-btn"
                    size="sm"
                    rounded
                    style="color: #2c37b4"
                    @click="openFitment(item[1].stock_code, item[1].sequence)"
                  >
                    <!--  @click="deleteFn(index, item.serial_no)" -->
                    <div class="fac word-wrap">
                      <!-- <img :src="defitIcon" /> -->
                      <span class="q-px-sm cap"> fit </span>
                    </div>
                  </q-btn>
                  <q-btn
                    class="q-px-sm q-ma-sm e-form-btn"
                    size="sm"
                    rounded
                    style="color: #b42c2c"
                    @click="defitmentFn(item[1].stock_code, item[1].serial_no)"
                  >
                    <!--  @click="deleteFn(index, item.serial_no)" -->
                    <div class="fac word-wrap">
                      <!-- <img :src="defitIcon" /> -->
                      <span class="q-px-sm cap"> defit </span>
                    </div>
                  </q-btn>
                </div>
              </span>
            </div>
          </div>

          <div v-if="item[1].last_status">
            <div class="row justify-end items-center">
              <q-btn flat color="primary" icon="history" @click="openOrderHistoryFn(item[1].stock_code,item[1].serial_no)"></q-btn>
              <div
                class="status-box"
                :class="getOrderStatusColor(item[1].last_status)"
              ></div>
              <div class="word-wrap">
                {{ item[1].last_status }}
              </div>
            </div>
            <div class="word-wrap" v-if="item[1].last_check_out">
              last check out: {{ item[1].last_check_out.split('T')[0] }}
            </div>
            <div class="word-wrap" v-if="item[1].last_check_out">
              last check out: {{ item[1].last_check_out.split('T')[0] }}
            </div>
          </div>
        </q-card-section>

        <q-tooltip class="bg-indigo" :offset="[10, 10]">
          <div class="text-left">
            <div
              v-for="(p, index) in getPartsStatus(
                item[1].serial_no,
                item[1].stock_code,
                item[1].sw_ver,
                item[1].hw_ver
              )?.split(',')"
              :key="index"
            >
              {{ p }}
            </div>
          </div>
        </q-tooltip>
      </div>
    </div>
  </ScrollArea>
</template>
<script setup lang="ts">
import {
  Child,
  ChildStockItem,
  Parent,
  Parts,
  StockItem,
} from 'src/services/type';
import { usePartsChildMapStore } from 'src/stores/partsChildMapStore';
import FitmentBox from 'src/components/partsMaster/FitmentBox.vue';
import { computed, ref } from 'vue';
import { part_fitment } from 'src/services/repairService';
import {
  assignChildParts,
  getChildPartsList,
  removeChildParts,
} from 'src/services/partsService';
import { useQuasar } from 'quasar';
import PartsMap from 'src/components/PartsMap.vue';
import { getDepotPartsBySerial } from 'src/services/depotService';
import { getPartsStatus, getOrderStatusColor } from 'src/utils/getPublic';
import defitIcon from 'src/assets/style/defitment.png';
import MyDialog from '../container/MyDialog.vue';
import ScrollArea from 'src/components/ScrollArea.vue';
import OrderHistorylv2Table from 'src/components/orderHistory/OrderHistorylv2Table.vue'
import MyBigDialog from '../container/MyBigDialog.vue';

const props = defineProps<{
  style: 'list' | 'map' | 'card';
  partItem: Parts;
}>();

const rows = ref();

const filterRows = computed(() => {
  return rows.value;
});

const openOrderHistory = ref(false)

const stock_code = ref('')
const serial_no = ref('')

const newfitmentDialog = ref(false);
const defitmentDialog = ref(false);
const editedRow = ref();
const $q = useQuasar();

const emit = defineEmits(['updateChild']);
const parent = ref<Parent>();
const childs = ref<Child[]>();

async function initData() {
  const res = await getDepotPartsBySerial(
    props.partItem.serial_no,
    props.partItem.stock_code
  );
  parent.value = res.data as Parent;
}

async function fitment(string: string) {
  if (string.includes('{') && string.includes('}')) {
    const obj = JSON.parse(string);
    const res = await assignChildParts(
      obj.CAT,
      obj.SN,
      props.partItem.stock_code,
      props.partItem.serial_no,
      editedRow.value.sequence
    );
    if (res.data) {
      if (res.data.code == 0) {
        $q.notify({
          color: 'negative',
          position: 'bottom',
          message: res.data.message,
        });
        return;
      }
      if (res.data.code == 1) {
        $q.notify({
          color: 'positive',
          position: 'bottom',
          message: 'success',
        });
      }
    }
  } else {
    /*     console.log(editedRow.value);
    console.log(string);
    console.log(props.partItem.stock_code);
    console.log(props.partItem.serial_no); */

    const res = await assignChildParts(
      editedRow.value.stock_code,
      string,
      props.partItem.stock_code,
      props.partItem.serial_no,
      editedRow.value.sequence
    );
    if (res.data) {
      if (res.data.code == 0) {
        $q.notify({
          color: 'negative',
          position: 'bottom',
          message: res.data.message,
        });
        return;
      }
      if (res.data.code == 1) {
        $q.notify({
          color: 'positive',
          position: 'bottom',
          message: 'success',
        });
      }
    }
  }
  newfitmentDialog.value = false;
  init();
  initData();
  emit('updateChild');
}

async function defitment() {
  const res = await removeChildParts(
    editedRow.value.stock_code,
    editedRow.value.serial_no,
    props.partItem.stock_code,
    props.partItem.serial_no
  );
  if (res.data) {
    $q.notify({
      color: 'positive',
      message: `${res.data.message}`,
    });
    init();
    emit('updateChild');
  }
  defitmentDialog.value = false;
  init();
  emit('updateChild');
}

function defitmentFn(stock_code: string, serial_no: string) {
  editedRow.value = { stock_code, serial_no };
  defitmentDialog.value = true;
}

function openFitment(stock_code: string, sequence: number) {
  editedRow.value = { stock_code, sequence };
  console.log(editedRow.value);

  newfitmentDialog.value = true;
}

async function getChildPartsListData() {
  const res = await getChildPartsList(
    props.partItem.stock_code,
    props.partItem.serial_no
  );
  if (res.data) {
    rows.value = res.data;
  }
}

function openOrderHistoryFn(sc:string, sn: string){
  stock_code.value = sc
  serial_no.value = sn
  openOrderHistory.value = true
}
const partsMap = ref<typeof PartsMap>();

function init() {
  /*   getChildPartsListData(); */
  initData();
}

init();
</script>

<style scoped>
.box {
  display: inline-table;
  width: 20px;
  height: 100px;
  margin: 3px;
  color: black;
  border: solid black 1px;
  background-color: white;
}

.inner-box {
  writing-mode: vertical-lr;
  text-orientation: upright;
  font-size: 1rem;
}

.outer-box {
  display: flex;
  flex-wrap: wrap;
  background-color: #d9d9d9;
  width: fit-content;
  padding: 3px;
}

.box-container {
  display: flex;
  align-items: start;
}
table {
  border-collapse: collapse;
  table-layout: fixed;
}

table tbody tr {
}
td {
  padding: 0.5rem;
}

table thead {
  top: 0;
  background-color: white;
  z-index: 10;
}

.non-editable {
  pointer-events: none;
}

.editable {
  background-color: #94cde7;
}

.test {
  flex-wrap: wrap;
}
</style>
